// 3. HTTP Client类
package com.ruoyi.teaching.http;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.system.domain.TeachingDesign;
import com.ruoyi.system.domain.TeachingDesignContent;
import com.ruoyi.system.service.ITeachingDesignService;
import com.ruoyi.system.service.ITeachingDesignContentService;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.*;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;

@Service
public class TeachingDesignHttpClient {

    @Autowired
    private ITeachingDesignService teachingDesignService;
    @Autowired
    private ITeachingDesignContentService teachingDesignContentService;

    // AI生成教学设计API URL
    private static final String API_URL = "http://127.0.0.1:88/v1"; // 基础 URL
    private static final String API_KEY = "app-oXxj1wJDCoe7ZtlpF0e2TLLZ"; // 新的 API Key
    private static final OkHttpClient client = new OkHttpClient.Builder()
        .connectTimeout(100, TimeUnit.SECONDS)
        .readTimeout(100, TimeUnit.SECONDS)
        .writeTimeout(100, TimeUnit.SECONDS)
        .build();

    /**
     * 请求AI生成教学设计
     */
    public SseEmitter generateTeachingDesign(String subject, Long teacherId, Long classId, String title) {
        // 构建请求体
        StringBuilder jsonBodyBuilder = new StringBuilder();
        jsonBodyBuilder.append("{");
        jsonBodyBuilder.append("\"query\": \"").append(subject).append("课程的全部内容\",");
        jsonBodyBuilder.append("\"user\": \"teacher_").append(teacherId).append("\",");
        jsonBodyBuilder.append("\"response_mode\": \"streaming\",");
        jsonBodyBuilder.append("\"inputs\": {}");
        jsonBodyBuilder.append("}");

        String jsonData = jsonBodyBuilder.toString();
        System.out.println("发送教学设计生成请求: " + jsonData);

        // 创建教学设计记录，等待填充内容
        TeachingDesign teachingDesign = new TeachingDesign();
        teachingDesign.setTitle(title != null && !title.isEmpty() ? title : subject + "教学设计");
        teachingDesign.setTeacherId(teacherId);
        teachingDesign.setClassId(classId);
        teachingDesign.setPrompt(subject);
        teachingDesign.setVersion(1L);
        teachingDesign.setStatus(0L);
        teachingDesign.setCreateTime(new Date());
        teachingDesign.setDelFlag("0");

        // 构建请求
        MediaType mediaType = MediaType.parse("application/json");
        RequestBody body = RequestBody.create(mediaType, jsonData);

        Request request = new Request.Builder()
            .url(API_URL + "/chat-messages")
            .header("Authorization", "Bearer " + API_KEY)
            .header("Content-Type", "application/json")
            .header("Accept", "text/event-stream")
            .post(body)
            .build();

        // 创建SseEmitter实例，0L表示不超时
        SseEmitter emitter = new SseEmitter(0L);
        System.out.println("创建SseEmitter实例");

        // 定义一个StringBuilder来累积AI回复内容
        StringBuilder aiResponseBuilder = new StringBuilder();

        // 在新线程中执行请求，避免阻塞
        new Thread(() -> {
            try (Response response = client.newCall(request).execute()) {
                if (!response.isSuccessful()) {
                    System.out.println("请求失败: " + response.code());
                    emitter.completeWithError(new Exception("API请求失败: " + response.code()));
                    return;
                }
                System.out.println("请求成功");

                if (response.body() != null) {
                    try (BufferedReader reader = new BufferedReader(
                        new InputStreamReader(response.body().byteStream()))) {
                        String line;
                        StringBuilder eventBuilder = new StringBuilder();
                        String eventName = null;

                        while ((line = reader.readLine()) != null) {
                            System.out.println("接收到行: " + line);

                            if (line.isEmpty()) {
                                // 省略
                            } else if (line.startsWith("event:")) {
                                eventName = line.substring(6).trim();
                            } else if (line.startsWith("data:")) {
                                String data = line.substring(5).trim();
                                eventBuilder.append(data);

                                try {
                                    JSONObject jsonObject = JSONObject.parseObject(data);

                                    // 处理逐块answer
                                    if (jsonObject.containsKey("event") && "message".equals(jsonObject.getString("event"))) {
                                        String answer = jsonObject.getString("answer");
                                        if (answer != null) {
                                            aiResponseBuilder.append(answer);

                                            // 向前端发送流式内容
                                            JSONObject streamData = new JSONObject();
                                            streamData.put("chunk", answer);
                                            emitter.send(SseEmitter.event().name("chunk").data(streamData.toJSONString()));
                                        }
                                    }

                                    // 处理workflow_finished，提取outputs.answer作为最终内容
                                    if (jsonObject.containsKey("event") && "workflow_finished".equals(jsonObject.getString("event"))) {
                                        System.out.println("【调试】收到workflow_finished事件");

                                        JSONObject dataObj = jsonObject.getJSONObject("data");
                                        if (dataObj != null && dataObj.containsKey("outputs")) {
                                            JSONObject outputs = dataObj.getJSONObject("outputs");
                                            String finalContent = outputs.getString("answer");
                                            System.out.println("【调试】最终AI生成教学设计内容如下：\n" + finalContent);

                                            // 保存AI原始回复
                                            teachingDesign.setAiResponse(finalContent);

                                            // 解析教学设计内容并保存
                                            parseAndSaveTeachingDesign(finalContent, teachingDesign);

                                            // 通知前端教学设计已保存
                                            JSONObject resultJson = new JSONObject();
                                            resultJson.put("status", "success");
                                            resultJson.put("message", "教学设计已生成并保存");
                                            resultJson.put("designId", teachingDesign.getId());
                                            emitter.send(SseEmitter.event().name("design_saved").data(resultJson.toJSONString()));
                                        }
                                    }
                                } catch (Exception e) {
                                    // JSON解析失败，不处理
                                    System.err.println("【调试】解析AI返回JSON异常: " + e.getMessage() + "；内容=" + data);
                                }
                            }
                        }
                    }
                }

                // 完成发射器
                emitter.complete();

            } catch (IOException e) {
                System.err.println("流式传输错误: " + e.getMessage());
                e.printStackTrace();
                emitter.completeWithError(e);
            }
        }).start();

        return emitter;
    }

    /**
     * 解析AI生成的教学设计内容并保存到数据库
     */
    private void parseAndSaveTeachingDesign(String content, TeachingDesign teachingDesign) {
        try {
            System.out.println("【调试】收到待解析AI教学设计原文：\n" + content);

            // 查询同一课程最新版本号
            Long latestVersion = teachingDesignService.selectLatestVersionByClassAndTeacher(
                teachingDesign.getClassId(),
                teachingDesign.getTeacherId()
            );

            // 新版本号 = 最新版本号 + 1，如果没有则从1开始
            teachingDesign.setVersion(latestVersion != null ? latestVersion + 1 : 1L);


            // 保存主表信息
            teachingDesignService.insertTeachingDesign(teachingDesign);

            // 解析教学设计内容部分
            parseAndSaveSection(content, "&课程概述和设计目标&", "overview", teachingDesign);
            parseAndSaveSection(content, "&课程章节&", "chapters", teachingDesign);
            parseAndSaveSection(content, "&考核方案&", "assessment", teachingDesign);
            parseAndSaveSection(content, "&评分详细标准&", "scoring", teachingDesign);
            parseAndSaveSection(content, "&预计成果&", "outcome", teachingDesign);

            // 更新设计状态为完成
            teachingDesign.setStatus(1L);
            teachingDesignService.updateTeachingDesign(teachingDesign);

            System.out.println("【调试】教学设计解析与保存流程完成。");
        } catch (Exception e) {
            e.printStackTrace();
            System.err.println("解析教学设计失败: " + e.getMessage());
        }
    }

    /**
     * 解析并保存特定部分的内容
     */
    private void parseAndSaveSection(String content, String sectionName, String contentType, TeachingDesign design) {
        try {
            Pattern pattern = Pattern.compile(sectionName + "\\s*\\$%([\\s\\S]*?)\\$%");
            Matcher matcher = pattern.matcher(content);

            if (matcher.find()) {
                String sectionContent = matcher.group(1).trim();
                System.out.println("【调试】解析到" + sectionName + "内容：\n" + sectionContent);

                // 保存到内容表
                TeachingDesignContent designContent = new TeachingDesignContent();
                designContent.setDesignId(design.getId());
                designContent.setContentType(contentType);
                designContent.setContent(sectionContent);
                designContent.setCreateTime(new Date());
                designContent.setUpdateTime(new Date());

                teachingDesignContentService.insertTeachingDesignContent(designContent);
                System.out.println("【调试】" + sectionName + "内容保存成功");
            } else {
                System.out.println("【调试】未找到" + sectionName + "部分内容");
            }
        } catch (Exception e) {
            System.err.println("解析" + sectionName + "部分失败: " + e.getMessage());
            e.printStackTrace();
        }
    }
}
